/**********************************************************************
Compile : gcc -O3 -o packing packing.c
Usage : ./packing N L M inputfile outfile
ion III
N     : number of the nodes
L     : number of the steps
M     :
inputfile
outfile
**********************************************************************/

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[])
{
	int N, L, M, number;

	N = atoi (argv[1]);
	L = atoi (argv[2]);
	M = atoi (argv[3]);

	FILE *fp, *fp2;
	char buf[256], filename[256];
	int i, j, k, p, p2, pathway[8][L][N];
	char packing[L][N];

	fp = fopen (argv[4], "r");
	p = p2 = number = 0;
	sprintf (filename, "%s-%04d", argv[5], p2);
	fp2 = fopen (filename, "w");
	fwrite (&M, sizeof (int), 1, fp2);
	fwrite (&N, sizeof (int), 1, fp2);
	fwrite (&L, sizeof (int), 1, fp2);
	while (fgets (buf, 256, fp))
	{
		if (p == 8 || buf[0] != 'c')
		{
			for (i = 0; i < L; i++)
			{
				for (j = 0; j < N; j++)
				{
					for (k = 0; k < p; k++)
					{
						if (pathway[k][i][j] == 1)
						{
							packing[i][j] |= (1<<k);
						}
						else
						{
							packing[i][j] &= ~(1<<k);
						}
					}
				}
			}

			fwrite (packing, sizeof (char), N * L, fp2);

			if (buf[0] != 'c')
				break;
			else
				p = 0;
		}

		if (number == M)
		{
			fclose (fp2);
			p2 ++;
			sprintf (filename, "%s-%04d", argv[5], p2);
			fp2 = fopen (filename, "w");
			fwrite (&M, sizeof (int), 1, fp2);
			fwrite (&N, sizeof (int), 1, fp2);
			fwrite (&L, sizeof (int), 1, fp2);
			number = 0;
		}

		for (i = 0; i < L; i++)
		{
			for (j = 0; j < N; j++)
			{
				fscanf (fp, "%d", &pathway[p][i][j]);
			}
			fgets (buf, 256, fp);
		}

		p ++;
		number ++;
	}

	fclose (fp);

	if (number != M)
	{
		rewind (fp2);
		fwrite (&number, sizeof (int), 1, fp2);
		fclose (fp2);
	}
}
